package com.example.kingdeescan;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import com.example.kingdeescan.dto.DocInfoDTO;
import com.example.kingdeescan.dto.ScanResultDTO;
import com.example.kingdeescan.enums.MessageType;
import com.example.kingdeescan.impl.FragmentServiceImpl;
import com.example.kingdeescan.interfaces.FragmentService;
import com.example.kingdeescan.interfaces.FragmentServiceListener;
import com.example.kingdeescan.ui.dtype.DTypeFragment;
import com.example.kingdeescan.ui.recored.RecoredFragment;
import com.example.kingdeescan.ui.scan.ScanFragment;
import com.example.kingdeescan.ui.search.SearchFragment;
import com.example.kingdeescan.utils.DBConfig;
import com.example.kingdeescan.utils.DBUtil;
import com.google.android.material.navigation.NavigationView;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.List;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

import butterknife.ButterKnife;
import lombok.SneakyThrows;

/**
 * @author  : 2020/7/24
 * @date    : zly
 * @version : 1.1
 * @desc    : 使用单Activity多Fragment架构，引入Lombok和Butter Kinfe框架
 */
public class MainActivity extends AppCompatActivity implements
        DTypeFragment.FDTypeClickListener, RecoredFragment.FRecoredListener, FragmentServiceListener,
        SearchFragment.FSearchListener {

    public static final String TAG="MainActivity";

    private AppBarConfiguration mAppBarConfiguration;

    private NavigationView navigationView;
    private DrawerLayout drawer;

    private FragmentTransaction transaction;

    //数据库连接工具类
    public static DBUtil dbUtil;
    //数据库配置类
    public static DBConfig dbConfig;

    //存储单据信息
    public static DocInfoDTO docInfoDTO = new DocInfoDTO();
    //实例化Fragment服务接口实现类
    public static FragmentService fragmentService=new FragmentServiceImpl();

    //处理消息Handler
    Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what)
            {
                case MessageType.MESSAGE_DBS_CONN_FAIL:
                    Toast.makeText(getApplicationContext(), "连接服务器数据库超时！", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    @SneakyThrows
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //绑定初始化ButterKnife
        ButterKnife.bind(this);
        //初始化布局组件
        initComponent();
        //初始化相关工具类和配置类
        initUtilsAndConfigs();
        //连接数据库
        connSqlByThread();
    }

    /**
     * 初始化布局组件
     */
    private void initComponent() {
        //获取并设置标题栏
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        //获取抽屉布局并设置监听
        drawer = findViewById(R.id.drawer_layout);
        //获取导航视图并设置菜单监听，对应上面实现的接口
        navigationView = findViewById(R.id.nav_view);
        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        mAppBarConfiguration = new AppBarConfiguration.Builder(
                R.id.nav_dtype, R.id.nav_recored, R.id.nav_scan,
                R.id.nav_search, R.id.nav_share, R.id.nav_send)
                .setDrawerLayout(drawer)
                .build();
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
        NavigationUI.setupWithNavController(navigationView, navController);
    }

    /**
     * 初始化相关工具类和配置类
     */
    private void initUtilsAndConfigs(){
        dbUtil=new DBUtil();
        dbConfig=new DBConfig();

        dbConfig.setIp("10.0.2.2");//10.0.2.2用于模拟器访问本地ip ，真机调试 192.168.1.130
        dbConfig.setDbUser("sa");
        dbConfig.setDbPwd("zly19990717");
        dbConfig.setDbName("XJM2019");
        dbConfig.initSqlCon();//初始化数据库连接语句
    }

    /**
     * 初始化时连接数据库，避免重复连接(使用多线程处理，避免堵塞主线程)
     * @throws SQLException
     */
    private void connSqlByThread() throws SQLException {
        if (!dbUtil.isConnOpened() && null!=dbConfig){
            new Thread(() -> {
                try {
                    dbUtil.getDBConn(dbConfig);//连接数据库
                } catch (Exception e) {
                    e.printStackTrace();
                    Message message=new Message();
                    message.what= MessageType.MESSAGE_DBS_CONN_FAIL;
                    handler.sendMessage(message);
                }
            }).start();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    /**
     * 拦截系统Back键的点击事件（因为系统的back键会直接关闭Activity而非切换Fragment）
     * @return
     */
    @Override
    public boolean onSupportNavigateUp() {
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        return NavigationUI.navigateUp(navController, mAppBarConfiguration)
                || super.onSupportNavigateUp();
    }

    /**
     * Fragment切换
     * @param currentFragment
     * @param targetFragment
     */
    public void showFragment(Fragment currentFragment, Fragment targetFragment) {
        //切换fragment布局
        transaction = getSupportFragmentManager().beginTransaction();

        //如果之前没有添加过
        if (!targetFragment.isAdded()) {
            transaction
                    .hide(currentFragment)
                    .add(R.id.nav_host_fragment, targetFragment, targetFragment.getClass().getName());//第三个参数为当前的fragment绑定一个tag，tag为当前绑定fragment的类名
        } else {
            transaction
                    .hide(currentFragment)
                    .show(targetFragment);
        }

        transaction.commit();
    }

    /**
     * 显示软键盘
     * @param view
     */
    public void showSoftInput(View view){
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            view.requestFocus();
            imm.showSoftInput(view, 0);
        }
    }

    /**
     * 隐藏软键盘
     * @param view
     */
    public void hideSoftInput(View view){
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    /**
     * 处理DTypeFragment中销售出库的点击的回调
     */
    @Override
    public void onFssckClick(View v) {
        Navigation.findNavController(v).navigate(R.id.action_nav_dtype_to_nav_recored);//执行action，跳转到对应的Fragment
    }

    /**
     * 处理RecoredFragment中确认按钮的点击的回调
     * @param v
     * @param recoredStatus
     */
    @Override
    public void onFRecoredCommitClick(View v,Bundle recoredStatus) {
        Navigation.findNavController(v).navigate(R.id.action_nav_recored_to_nav_scan,recoredStatus);//执行action，跳转到对应的Fragment
    }

    /**
     * 处理RecoredFragment中单据编号生成失败事件的回调
     * @param v
     */
    @Override
    public void onFBillNoCreatedFailEvent(View v) {
        Navigation.findNavController(v).navigate(R.id.action_nav_recored_to_nav_dtype);//执行action，跳转到对应的Fragment
    }

    /**
     * 处理RecoredFragment中编辑框的点击回调
     * @param v
     * @param searchType
     *      搜索类型
     */
    @Override
    public void onFRecoredEditTextClick(View v,Bundle searchType) {
        Navigation.findNavController(v).navigate(R.id.action_nav_recored_to_nav_search,searchType);//执行action，跳转到对应的Fragment
    }

    /**
     * 处理SearchFragment中确认按钮的点击回调
     * @param v
     * @param bundle
     */
    @Override
    public void onFSearchCommitClick(View v, Bundle bundle) {
        Navigation.findNavController(v).navigate(R.id.action_nav_search_to_nav_recored,bundle);//执行action，跳转到对应的Fragment
    }

    /**
     * 处理SearchFragment中搜索内容为空的回调
     * @param v
     */
    @Override
    public void onFSearchNonEvent(View v) {
        Navigation.findNavController(v).navigate(R.id.action_nav_search_to_nav_recored);//执行action，跳转到对应的Fragment
    }

    /**
     * 处理各Fragment中单据类型为空的回调
     */
    @Override
    public void onNonDocTypeEventListener(View v, Fragment fragment) {
        //RecoredFragment->DTypeFragment
        if (fragment instanceof RecoredFragment){
            Navigation.findNavController(v).navigate(R.id.action_nav_recored_to_nav_dtype);//执行action，跳转到对应的Fragment
        }
        //ScanFragment->RecoredFragment
        if (fragment instanceof ScanFragment){
            Navigation.findNavController(v).navigate(R.id.action_nav_scan_to_nav_recored);//执行action，跳转到对应的Fragment
        }
    }

    /**
     * 处理各Fragment中搜索类型为空的回调
     */
    @Override
    public void onNonSearchTypeEventListener(View v, Fragment fragment) {
        if (fragment instanceof SearchFragment){
            Navigation.findNavController(v).navigate(R.id.action_nav_search_to_nav_recored);//执行action，跳转到对应的Fragment
        }
    }

    @Override
    public void onInvalidInvokeFragmentEventListener(View v, Fragment fragment) {
        if (fragment instanceof ScanFragment){
            Navigation.findNavController(v).navigate(R.id.action_nav_scan_to_nav_recored);//执行action，跳转到对应的Fragment
        }
    }
}
